package com.heng.application.page

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.SharedPreferences
import android.os.Bundle
import android.os.IBinder
import android.preference.PreferenceManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.RadioButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.heng.application.R
import com.heng.application.service.ServiceGo
import com.heng.application.utils.GoUtils

/**
 * @Author    : zhangheng227
 * date       : 2025/5/26
 */
class MainActivity : AppCompatActivity() {


    companion object{
        const val LAT_MSG_ID = "LAT_VALUE"
        const val LNG_MSG_ID = "LNG_VALUE"
        const val ALT_MSG_ID = "ALT_VALUE"

        const val POI_NAME = "POI_NAME"
        const val POI_ADDRESS = "POI_ADDRESS"
        const val POI_LONGITUDE = "POI_LONGITUDE"
        const val POI_LATITUDE = "POI_LATITUDE"
    }

    private var mConnection: ServiceConnection? = null
    private var mServiceBinder: ServiceGo.ServiceGoBinder? = null
    private var isMockServStart = false
    private var sharedPreferences: SharedPreferences? = null
    private var lon: Double = 0.0
    private var lat: Double = 0.0
    private var alt: Double = 0.0
    private var poiName: String? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        mConnection = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName, service: IBinder) {
                mServiceBinder = service as ServiceGo.ServiceGoBinder
            }

            override fun onServiceDisconnected(name: ComponentName) {}
        }

        initView()
    }

    private fun initView() {
        val inputPosBtn: ImageButton = findViewById(R.id.input_pos)
        inputPosBtn.setOnClickListener { v: View? ->
            val dialog: AlertDialog
            val builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle("请输入经度和纬度")
            val view: View =
                LayoutInflater.from(this@MainActivity).inflate(R.layout.location_input, null)
            builder.setView(view)
            dialog = builder.show()
            val dialog_lng = view.findViewById<EditText>(R.id.joystick_longitude)
            val dialog_lat = view.findViewById<EditText>(R.id.joystick_latitude)
            val rbBD = view.findViewById<RadioButton>(R.id.pos_type_bd)
            val btnGo = view.findViewById<Button>(R.id.input_position_ok)
            btnGo.setOnClickListener { v2: View? ->
                val dialog_lng_str = dialog_lng.text.toString()
                val dialog_lat_str = dialog_lat.text.toString()
                if (TextUtils.isEmpty(dialog_lng_str) || TextUtils.isEmpty(dialog_lat_str)) {
                    GoUtils.DisplayToast(
                        this@MainActivity,
                        resources.getString(R.string.app_error_input)
                    )
                } else {
                    val dialog_lng_double = dialog_lng_str.toDouble()
                    val dialog_lat_double = dialog_lat_str.toDouble()
                    if (dialog_lng_double > 180.0 || dialog_lng_double < -180.0) {
                        GoUtils.DisplayToast(
                            this@MainActivity,
                            resources.getString(R.string.app_error_longitude)
                        )
                    } else {
                        if (dialog_lat_double > 90.0 || dialog_lat_double < -90.0) {
                            GoUtils.DisplayToast(
                                this@MainActivity,
                                resources.getString(R.string.app_error_latitude)
                            )
                        } else {
                            lon = dialog_lng_double
                            lat = dialog_lat_double
                            if (rbBD.isChecked) {
//                                MainActivity.mMarkLatLngMap =
//                                    LatLng(dialog_lat_double, dialog_lng_double)
                            } else {
//                                val bdLonLat: DoubleArray =
//                                    MapUtils.wgs2bd09(dialog_lat_double, dialog_lng_double)
//                                MainActivity.mMarkLatLngMap = LatLng(bdLonLat[1], bdLonLat[0])
                            }
//                            MainActivity.mMarkName = "手动输入的坐标"
//                            markMap()
//                            val mapstatusupdate: MapStatusUpdate =
//                                MapStatusUpdateFactory.newLatLng(MainActivity.mMarkLatLngMap)
//                            MainActivity.mBaiduMap.setMapStatus(mapstatusupdate)

                            dialog.dismiss()
                        }
                    }
                }
            }
            val btnCancel = view.findViewById<Button>(R.id.input_position_cancel)
            btnCancel.setOnClickListener { v1: View? -> dialog.dismiss() }
        }

        val testMockTv: TextView = findViewById(R.id.testMockTv)
        testMockTv.setOnClickListener {
            startGoLocation()
        }
    }

    private fun startGoLocation() {
        val serviceGoIntent = Intent(this@MainActivity, ServiceGo::class.java)
        if (mConnection == null) {
            return
        }
        bindService(serviceGoIntent, mConnection!!, BIND_AUTO_CREATE) // 绑定服务和活动，之后活动就可以去调服务的方法了
        val latLng: DoubleArray = GoUtils.bd2wgs(
          lon,
          lat
        )
        serviceGoIntent.putExtra(LNG_MSG_ID, latLng[0])
        serviceGoIntent.putExtra(LAT_MSG_ID, latLng[1])
        val alt: Double = sharedPreferences?.getString("setting_altitude", "55.0")?.toDouble() ?: 55.0
        serviceGoIntent.putExtra(ALT_MSG_ID, alt)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForegroundService(serviceGoIntent)
        } else {
            startService(serviceGoIntent)
        }
        isMockServStart = true
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isMockServStart) {
            unbindService(mConnection!!) // 解绑服务，服务要记得解绑，不要造成内存泄漏
            val serviceGoIntent = Intent(this@MainActivity, ServiceGo::class.java)
            stopService(serviceGoIntent)
        }
    }
}